<?php
namespace frontend\controllers;
header("Content-type:text/html;charset=utf-8");

use backend\models\course\Course;
use Yii;
use common\models\LoginForm;
use frontend\models\PasswordResetRequestForm;
use frontend\models\ResetPasswordForm;
use frontend\models\SignupForm;
use frontend\models\ContactForm;
use frontend\models\User;
use frontend\models\search\Search;
use backend\models\system\BannerGroup;
use backend\models\system\Banner;
use backend\models\course\course_type;
use backend\models\user\TeacherInfo;
use backend\models\system\SysConfig;
use backend\models\article\Article;
use backend\models\article\Page;
use frontend\models\question\Question;
use frontend\models\download\Download;
use yii\base\InvalidParamException;
use yii\web\BadRequestHttpException;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use frontend\models\register\RegisterForm;
use common\components\Easemob;
/**
 * Site controller
 */

class SiteController extends Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'only' => ['logout', 'signup'],
                'rules' => [
                    [
                        'actions' => ['signup'],
                        'allow' => true,
                        'roles' => ['?'],
                    ],
                    [
                        'actions' => ['logout'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'logout' => ['post'],
                ],
            ],
        ];
    }

    /**
     * @inheritdoc
     */
    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
            'captcha' => [
                'class' => 'yii\captcha\CaptchaAction',
                'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
            ],
            'auth' => [
                'class' => 'yii\authclient\AuthAction',
                'successCallback' => [$this, 'successCallback'],
            ],
        ];
    }

    /**
     * Displays homepage.
     *
     * @return mixed
     */
    public function actionIndex()
    {
	    //$banner = BannerGroup::find()->with("banneropen")->where("group_isshow = 1")->asArray()->all();
	    /* 轮播图 */
	    $bannergroup = Banner::getGroups();

	    /* 直播课程 */
	    $livemessage = Course::directmessage(4);

	    /* 视频课程 */
	    $videomessage = Course::videomessage(4);

	    /* 名师风采 */
	    $teacherrmd = TeacherInfo::teacherrmd(5);

	    /* 友情链接 */
	    $friend_link = Yii::$app->params['sysconfig']['FRIEND_LINK'];

	    /* 关于我们 */
	    $page = new Page;
    	$about = $page -> Page();

	    /* 网站导航 */
	    $web_nav = Yii::$app->params['sysconfig']["'TOP_NAV'"];
	    foreach($web_nav as $k=>$v){
		    $web_nav[$k] = unserialize($v);
	    }

	    /* 微信二维码 */
	    $wechat_code = Yii::$app->params['sysconfig']["'CUSTOMER_SERVICE'"]["'WECHAT_CODE'"];

	    return $this->render('index',['bannergroup'=>$bannergroup,'livemessage'=>$livemessage,'videomessage'=>$videomessage,'teacherrmd'=>$teacherrmd,'friend_link'=>$friend_link,'about'=>$about,'web_nav'=>$web_nav,'wechat_code'=>$wechat_code]);
    }

    /**
     * @inheritdoc  第三方登陆回调
     */
    public function actionSuccesscallback($code)
    {
		$grant_type = 'authorization_code';
		$client_id = \Yii::$app->params['Qq']['clientId'];
		$client_secret = \Yii::$app->params['Qq']['clientSecret'];
		$url = 'https://graph.qq.com/oauth2.0/token?code='.$code.'&grant_type='.$grant_type.'&client_id='.$client_id.'&client_secret='.$client_secret.'&redirect_uri=http://www.bwphp.com/index.php/site/successcallback';
		$data = file_get_contents($url);
		$data = explode('&',$data);
		foreach($data as $k=>$v){
			$datas[] = explode('=',$v);
		}
		foreach($datas as $k=>$v){
			$cond[$v[0]] = $v[1];
		}
		$url = 'https://graph.qq.com/oauth2.0/token?code='.$code.'&grant_type=refresh_token&client_id='.$client_id.'&client_secret='.$client_secret.'&refresh_token='.$cond['refresh_token'];
		$data = file_get_contents($url);
		$data = explode('&',$data);
		foreach($data as $k=>$v){
			$datas[] = explode('=',$v);
		}
		foreach($datas as $k=>$v){
			$cond[$v[0]] = $v[1];
		}
		$access_token = $cond['access_token'];
		$url = 'https://graph.qq.com/oauth2.0/me?access_token='.$access_token;
		$data = file_get_contents($url);
		$data = substr($data,'10','-3');
		$data = json_decode($data);
		$openid = $data->openid;
		$re = User::find()->where(['user_openid'=>$openid])->asarray()->one();
		if(empty($re)){
			$oauth_consumer_key = $data->client_id;
			$url = 'https://graph.qq.com/user/get_user_info?access_token='.$access_token.'&oauth_consumer_key='.$oauth_consumer_key.'&openid='.$openid;
			$data = file_get_contents($url);
			$data = json_decode($data);
			$sysconfig = new SysConfig();
			$sysconfig->config_key = "default_photo";
			$re = $sysconfig->getValueBykey();
			$user = new User();
			$user->user_thumb = $re['config_value'];
			if($data->gender == '男'){
				$sex = 1;
			}else{
				$sex = 0;
			}
			$user->user_sex = $sex;
			$user->user_openid = $openid;
			$user->user_opentype = 1;
			$user->user_regip = Yii::$app->request->userIP;
			$user->user_regtime = time();
			$user->user_pwd = md5(time());
			if($user->Save(false)){
				$user_id = $user->db->getLastInsertID();
				$user =User::find()->where(['user_id'=>$user_id])->one();
				$user->user_name = substr(md5('11'.$user_id),10,18);
				$user->user_num='11'.$user_id;
				$user->user_emid=md5($openid);
				$user->save();
				$em = new Easemob();
				$options['username']='11'.$user_id;
				$options['password']=md5($openid);
				$em->openRegister($options);
				$session = Yii::$app->session;
				$session->open();
				$session->set('user_id',$user_id);
				$session->set('user_thumb',$re['config_value']);
				$session->set('user_emid',md5($openid));
				$session->set('user_num','11'.$user_id);
				$session['captcha'] = [
					'number' => 5,
					'lifetime' => 3600,
				];
				$session->close();
				echo "<script>location.href='".\Yii::$app->urlManager->createUrl('site/index')."'</script>";
			}
		}else{
				$session = Yii::$app->session;
				$session->open();
				$session->set('user_id',$re['user_id']);
				$session->set('user_thumb',$re['user_thumb']);
				$session->set('user_emid',$re['user_emid']);
				$session->set('user_num',$re['user_num']);
				$session['captcha'] = [
					'number' => 5,
					'lifetime' => 3600,
				];
				$session->close();
				echo "<script>location.href='".\Yii::$app->urlManager->createUrl('site/index')."'</script>";
		}
    }
    

    /**
     * 站点搜索
     */
    public function actionSearch()
    {
//	    $sql = 'SELECT * FROM `edu_course` WHERE course_id = :course_id';
//	    $params = [
//		    'course_id' => 43
//	    ];
//	    $rows = Yii::$app->sphinx->createCommand($sql, $params)->queryAll();
//	    print_r($rows);die;
	    if(Yii::$app->request->isGet) {
		    $search = Yii::$app->request->get("Search");
		    $search_content = $search['search_content'];
		    include("../web/Sphinxapi.php");
		    $sphinx = new \SphinxClient();//实例化sphinx
		    $sphinx->SetServer("101.200.211.218", 9312);//连接sphinx
		    $sphinx->SetArrayResult(true);//返回数组

		    //$sphinx->SetFilter("status",array("1"));
		    $data['course'] = $sphinx->query($search_content, "course_search");//查询课程数据
		    $data['course_zl'] = $sphinx->query($search_content, "course_zl");//查询课程数据
		    $data['soft'] = $sphinx->query($search_content, "soft_search");//查询下载数据
		    $data['soft_zl'] = $sphinx->query($search_content, "soft_zl");//查询下载数据
		    $data['article'] = $sphinx->query($search_content, "article_search");//查询行业资讯数据
		    $data['article_zl'] = $sphinx->query($search_content, "article_zl");//查询行业资讯数据
		    $data['teacher'] = $sphinx->query($search_content, "teacher_search");//查询师资力量数据
		    $data['teacher_zl'] = $sphinx->query($search_content, "teacher_zl");//查询师资力量数据
		    $data['question'] = $sphinx->query($search_content, "question_search");//查询下载数据
		    $data['question_zl'] = $sphinx->query($search_content, "question_zl");//查询下载数据
		    $count = 0;
		    foreach($data as $k=>$v)
		    {
			    $count+=$v['total'];
			    $arr[$k]['id']="";
			    if($v['matches']){
				    foreach($v['matches'] as $key=>$val)
				    {
					    $arr[$k]['id'].= ",".$val['id'];
				    }
			    }
		    }
		    $arr['course']['id'] = $arr['course']['id'].$arr['course_zl']['id'];
		    unset($arr['course_zl']['id']);
		    $arr['soft']['id'] = $arr['soft']['id'].$arr['soft_zl']['id'];
		    unset($arr['soft_zl']['id']);
		    $arr['article']['id'] = $arr['article']['id'].$arr['article_zl']['id'];
		    unset($arr['article_zl']['id']);
		    $arr['teacher']['id'] = $arr['teacher']['id'].$arr['teacher_zl']['id'];
		    unset($arr['teacher_zl']['id']);
		    $arr['question']['id'] = $arr['question']['id'].$arr['question_zl']['id'];
		    unset($arr['question_zl']['id']);
		    /* 查询直播课程 */
		    if(!empty($arr['course']['id'])){
			    $search['direct'] = Search::directseacher($arr['course']['id'],11);
			    $all_count['direct'] = Search::directcount($arr['course']['id'],11);
		    }else{
			    $search['direct'] = array();
			    $all_count['direct'] = 0;
		    }

			/* 查询视频课程 */
		    if(!empty($arr['course']['id'])){
			    $search['video'] = Search::directseacher($arr['course']['id'],2);
			    $all_count['video'] = Search::directcount($arr['course']['id'],2);
		    }else{
			    $search['video'] = array();
			    $all_count['video'] = 0;
		    }

		    /* 查询下载 */
		    if(!empty($arr['soft']['id'])){
			    $search['soft'] = Download::getSoft($arr['soft']['id']);
			    $all_count['soft'] = $data['soft']['words'][$search_content]['docs']+$data['soft_zl']['words'][$search_content]['docs'];
		    }else{
			    $search['soft'] = array();
			    $all_count['soft'] = 0;
		    }

		    /* 查询行业资讯 */
		    if(!empty($arr['article']['id'])){
			    $article = new Article();
			    $search['article'] = $article->getArticlesearch(substr($arr['article']['id'],1));
			    $all_count['article'] = count($search['article']);
			    $count = $count - ($data['article']['total']+$data['articlezl']['total']) + count($search['article']);
		    }else{
			    $search['article'] = array();
			    $all_count['article'] = 0;
		    }

		    /* 查询师资力量 */
		    if(!empty($arr['teacher']['id'])){
			    $search['teacher'] = Search::teacherseacher($arr['teacher']['id']);
			    $all_count['teacher'] = $data['teacher']['words'][$search_content]['docs']+$data['teacher_zl']['words'][$search_content]['docs'];
		    }else{
			    $search['teacher'] = array();
			    $all_count['teacher'] = 0;
		    }

		    /* 查询有问必答 */
		    if(!empty($arr['question']['id'])){
			    $search['question'] = Question::Question($arr['question']['id']);
			    $all_count['question'] = $data['question']['words'][$search_content]['docs']+$data['question_zl']['words'][$search_content]['docs'];
		    }else{
			    $search['question'] = array();
			    $all_count['question'] = 0;
		    }

		    return $this->render('search',[
			                                'search'            =>$search,
			                                'count'             =>$count,
			                                'all_count'         =>$all_count,
			                                'search_content'    =>$search_content,
		                                    ]);
	    }

    }


    /**
     * 站点单页面信息
     */
    public function actionSingle()
    {
    	$url = Yii::$app->request->get("url");
    	$model = new Page;
    	$data = $model -> Page();
	    foreach ($data as $key => $value) {
	    	if ($value['page_url'] == $url) {
	    		$sin = $key;
	    	}
	    }
	    $sin = $sin ? $sin : 0;
        return $this->render('single',['data' => $data,'sinval' => $sin]);
    }
}
